<?php
/*
 * Created on May 12, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pcategory extends MY_Controller {

    function __construct() {

        parent::__construct();

        $this->checkLogin();
        $this->checkPermission();
        $this->load->model('pcategory_model', 'pcategory', true);
        $this->template->set_template('admin');
        $this->buildMenu();
    }
    function Pcategory(){
       
        $this->load->library('xajax', 'category');
        //$this->xajax->registerFunction(array('setDisplay', &$this, 'setDisplay'));
        $this->xajax->registerFunction(array('changeBestSell', &$this, 'changeBestSell'));
        $this->xajax->registerFunction(array('changeSpecial', &$this, 'changeSpecial'));
        $this->xajax->registerFunction(array('changeDisplay', &$this, 'changeDisplay'));
        $this->xajax->processRequest();
        $this->xajax_js = $this->xajax->getJavascript($this->base_url.'js/');
        $this->load->model('pcategory_model', 'pcategory', true);
        $this->checkLogin();
        $this->checkPermission();
    }

    function changeBestSell($id){
        $this->load->model('product_model', 'product', true);
        $this->load->model('pcategory_model', 'pcategory', true);

        $category = $this->pcategory->getById($id);

        if($category){

            $category->best_sell = $category->best_sell==1? 0 : 1;

            $this->pcategory->update($category);

            $this->pcategory->applyBestSellProduct($id, $category->best_sell);

            $objResponse = new xajaxResponse();

            //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

            return $objResponse;
        }
    }

    function changeSpecial($id){
        $this->load->model('product_model', 'product', true);
        $this->load->model('pcategory_model', 'pcategory', true);

        $category = $this->pcategory->getById($id);

        if($category){

            $category->special = $category->special==1? 0 : 1;

            $this->pcategory->update($category);

            $this->pcategory->applySpecialProduct($id, $category->special);

            $objResponse = new xajaxResponse();

            //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

            return $objResponse;
        }
    }

    function changeDisplay($id){
        $this->load->model('product_model', 'product', true);
        $this->load->model('pcategory_model', 'pcategory', true);

        $category = $this->pcategory->getById($id);

        if($category){

            $category->active = $category->active==1? 0 : 1;

            $this->pcategory->update($category);

            $objResponse = new xajaxResponse();

            //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

            return $objResponse;
        }
    }

    function index(){
       // print_r($this->session->userdata('user'));
        // $this->template->render();
        $this->view();
    }

    function parseWhere($paremeters){
        $result = '';
        //if()
        $operation = '';

        foreach($paremeters as $para => $value){
            if($para == 'AND'){
                $operation = 'AND';
                $index = 1;
                $num = count($value);
                $result .= ' (';
                foreach($value as $p => $v){
                    if($p=='AND' OR $p=='OR'){
                        $result .=  $this->parseWhere($v) ;
                        //print_r($v);
                        //echo '<br>Nhanh con:...' . $this->parseWhere($value) . '...<br>';
                        //echo 'Goi de quy.';
                    }
                    else{ echo '<br> Goi phan d=> 12 <br>';
                        $result .= $p . '=' . $v;
                    }

                    if($index < $num)
                    $result .=  ' AND ';

                    $index++;
                }
                $result .= ' )';
            }
            if($para == 'OR'){
                $operation = 'OR';
                $index = 1;
                $num = count($value);
                $result .= ' (';
                foreach($value as $p => $v){
                    if($p=='AND' OR $p=='OR'){
                        $result .=  $this->parseWhere($value) ;
                        //print_r($v);
                        //echo '<br>Nhanh con:...' . $this->parseWhere($value) . '...<br>';
                        //echo 'Goi de quy.';
                    }
                    else{
                        $result .= $p . '=' . $v;
                    }

                    if($index < $num)
                    $result .=  ' OR ';

                    $index++;
                }
                $result .= ' )';
            }

        }

        return $result;
    }

    function create(){
       $data = array();
        $data['id_pcategory'] = 0;
        $data['code'] = '';
        $data['code_parent'] = '';
        $data['id_parent_pcategory'] = 0;
        $data['vi_name'] = '';
        $data['en_name'] = '';
        $data['vi_description'] = '';
        $data['en_description'] = '';
        $data['link_rewrite'] = '';
        $data['meta_title'] = '';
        $data['meta_keywords'] = '';
        $data['meta_description'] = '';
        $data['level_depth'] = 0;
        $data['active'] = 1;
        $data['date_add'] = date('Y-m-d H:i:s', time());
        $data['date_upd'] = date('Y-m-d H:i:s', time());


        
        
       // $data['category'] = $obj;
        $data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', '');
        $data['error_message'] = '';
        $data['legend_text'] = lang('create_product_category');
        $this->template->parse_view('content', 'admin/pcategory/create_pcategory', $data);
        $this->template->render();
       // $this->main = $this->load->view('admin/pcategory/create_pcategory', $data, true);
       // $this->execute();
    }

    function setDisplay($id){
        $this->load->model('pcategory_model', 'pcategory', true);
        $category = $this->pcategory->getById($id);

        if($category){
            $category->active = $category->active==1? 0 : 1;

            $this->category->update($category);

            $objResponse = new xajaxResponse();

            //$objResponse->assign("message" , "innerHTML",'Da cap nhat. ' );

            return $objResponse;
        }

    }

    function edit($id){
        $category = $this->pcategory->getById($id);
        
        if(!$category){
            redirect('admin/pcategory/view');
        }

        $data = $category;
        $data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', $data['code_parent']);
        $data['error_message'] = '';
        $data['legend_text'] = lang('edit_product_category');

        $this->template->parse_view('content', 'admin/pcategory/create_pcategory', $data);
        $this->template->render();
        
        //$this->main = $this->load->view('admin/pcategory/create_pcategory', $data, true);
        //$this->execute();
    }

    function create_from_file(){ //
        $error_message = '';
        if(isset($_FILES['file']['tmp_name'])){
            $config['upload_path'] = './Data/';
            $config['allowed_types'] = 'xls';
            //$config['overwrite'] = true;
            $config['max_size']	= 8192; // 8192 kb = 8mb
            //$config['max_width']  = '1024';
            //$config['max_height']  = '768';
            //$config['max_filename'] = 50;
            //$config['encrypt_name'] = true;
            //$config['remove_spaces'] = false;
            $result_upload = $this->uploadFile($config);
            if($result_upload['error']){

                $error_message = $result_upload['message'];
            }
            else{

                //if($result_upload['upload_data']['file_type']==)
                //echo $config['upload_path'].$result_upload['upload_data']['file_name'];
                //echo mime_content_type($config['upload_path'].$result_upload['upload_data']['file_name']);

                $this->load->library('excel/spreadsheet_Excel_Reader');

                $data = new Spreadsheet_Excel_Reader();

                $data->setOutputEncoding('utf-8');
                //$data->setOutputEncoding('windows-1258');
                //$data->setOutputEncoding('iso-8859-1');

                $data->read($config['upload_path'].$result_upload['upload_data']['file_name']);
                if(!isset($data->_ole->error)){
                    //$data->read('BG MBT 1P 4-2009.xls');
                    //$data->sheets[1]['cells'][2][3];
                    //$data->sheets[SHEET]['cells'][ROW][COLUMN];
                    //print_r($data);
                    error_reporting(E_ALL ^ E_NOTICE);
                    //$colspan = 1;
                    //echo "Sheet:".count($data->sheets);
                    //echo "Sheet:".$data->sheets[0]['numCols'];
                    $objects = array();
                    for($a = 0; $a < count($data->sheets); $a++){
                        //echo 'TEn sheet:' . $data->boundsheets[$a]['name'];
                        for ($i = 2; $i <= $data->sheets[$a]['numRows']; $i++) {
                            //if($data->sheets[$a]['numCols'] < 3) break;
                            //echo "<br>Row:".$data->sheets[$a]['cellsInfo'][1] .'_'. $i;
                            $obj = new stdClass();
                            $obj->id_parent_pcategory = 0;
                            //$obj->vi_name = '';
                            //$obj->en_name = '';
                            $obj->vi_description = '';
                            $obj->en_description = '';
                            $obj->number_product = 0;
                            $obj->link_rewrite = '';
                            $obj->meta_title = '';
                            $obj->meta_keywords = '';
                            $obj->meta_description = '';
                            $obj->level_depth = 0;
                            $obj->active = 1;
                            $obj->module = PRODUCTS_PAGE;
                            $obj->date_add = date('Y-m-d H:i:s', time());
                            $obj->date_upd = date('Y-m-d H:i:s', time());

                            $obj->code = trim($data->sheets[$a]['cells'][$i][1]);
                            $obj->code_parent = trim($data->sheets[$a]['cells'][$i][2]);
                            $obj->vi_name = trim($data->sheets[$a]['cells'][$i][3]);
                            $obj->en_name = trim($data->sheets[$a]['cells'][$i][3]);
                            if($obj->code!='' AND $obj->code!=null AND $obj->vi_name!='' AND $obj->vi_name!=null)
                            $objects[] = $obj;
                            //	break;
                            //if($obj->code!='' AND $obj->vi_name!='')
                            //$objects[] = $obj;

                                /*
                                for ($j = 1; $j <= $data->sheets[$a]['numCols']; $j++) {
                                    $value = $data->sheets[$a]['cells'][$i][$j];
                                    $colspan = $data->sheets[$a]['cellsInfo'][$i][$j]['colspan'];
                                    if($colspan){
                                        //echo "<td colspan='$colspan' style='border-bottom:1px solid black;'>". $value . "</td>\n";
                                    }
                                    else{
                                        if(!$value) $value = "&nbsp;";
                                        //echo "<td style='border-bottom:1px solid black;'>". $value . "</td>\n";
                                        $colspan = 1;
                                    }

                                } // for column
                                */

                        } //for row
                    } // for count sheet
                    if(count($objects)>0){
                        $result = $this->pcategory->create($objects);
                        if($result){
                            $this->pcategory->updateParentId();
                        }
                        @unlink($config['upload_path'].$result_upload['upload_data']['file_name']);
                        //redirect('admin/pcategory');
                        //return;
                    }

                } //if
                else{
                    $error_message .= 'The filename ' . $result_upload['upload_data']['file_name'] . ' is not readable';
                }

            }
        }
        $data = array();
        $data['error_message'] = '<div style="color:red">'.$error_message . '</div>';
        $this->main = $this->load->view('admin/pcategory/form_upload', $data, true);
        $this->execute();
    }

    function upload_image($field_name, $path, $allowed_types = '')
    {
        $result = array();
        $config['upload_path'] = $path; //'./Data/Images/';
        if($allowed_types == '')
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        else $config['allowed_types'] = $allowed_types;
        //$config['max_size']	= '1000';
        //$config['max_width']  = '1024';
        //$config['max_height']  = '768';
        $config['overwrite']  = false;


        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($field_name))
        {
            //$error = array('error' => $this->upload->display_errors());
            $result['error'] = true;
            $result['message'] = $this->upload->display_errors();
            //$this->load->view('upload_form', $error);
        }
        else
        {
            //$data = array('upload_data' => $this->upload->data());
            $result['error'] = false;
            $result['upload_data'] = $this->upload->data();
        }

        return $result;
    }

        /*function uploadFile($config){

            $this->load->library('upload', $config);
            $result = array('error' => false);

            if ( ! $this->upload->do_upload('file'))
            {
                $result['message'] = $this->upload->display_errors();
                $result['error'] = true;
            }
            else
            {
                $result['upload_data'] = $this->upload->data();

            }

            return  $result;
        }*/

    function view(){
        $this->load->library('pagination');

        $id_parent = intval($this->uri->segment(4));
        $_code_parent = $id_parent;
        $page = (int)$this->uri->segment(5);
        //if($code_parent=='') $_code_parent = '0';
        $base_url = $this->base_url . 'admin/pcategory/view/' . $id_parent. '/';

        //if($id_parent=='_') $id_parent = '';

        $parameters = array();

        $parameters['code_parent'] = $id_parent;
        //$parameters[' AND code'] = ' "MAYLANH';

        //$total_rows = $this->pcategory->countAll($code_parent);
        $total_rows = $this->pcategory->countAllAdmin($id_parent);

        $per_page = NUMBER_RECORD_PER_CATEGORY_PAGE;

        $uri_segment = 5;

        //$this->pagination->initialize($config);

        pagination($base_url, $total_rows, $per_page , $uri_segment);

        
        $pcategories = $this->pcategory->getAllAdmin($page, $per_page, $id_parent);


        if($page > 0 AND count($pcategories)==0){
            redirect('admin/pcategory/view/' . ($page-$per_page));
            return;
        }

        $track = getTrack($id_parent, null, $lang = 'vi' );

        $data = array();
        $data['rows'] = $pcategories;
        $data['track'] = $track;
        //$this->main = eval ($this->loadTemplate('admin/product/product_list.tpl'));
        //$this->main = $this->load->view('admin/pcategory/pcategory_list', $data, true);
        $this->template->parse_view('content', 'admin/pcategory/pcategory_list', $data);
        //$this->main = eval ($this->loadTemplate('admin/pcategory/pcategory_list.tpl'));
        $this->template->render();
    }

    function view_tree(){
        //$this->load->model('pcategory_model', 'category', true);
        $categories = $this->pcategory->getAll();
        $this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        //$name = 'Parent';
        $value = '';
        $selected = '';
        $space= '';
        $label = 'Parent';
        $class = '';
        $action = '';
        $style = '';

        $tmp = array();
        for($i = 0; $i <count($categories); $i++){
            $category = $categories[$i];
            //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
            $tmp[$category->code_parent][$category->code] = $category;
        }

        //$rows = $this->help_view_tree($tmp, $parent = '', $space = '&nbsp;');
        $rows = $this->help_view_tree($tmp, $parent = '', $space = '::');
        $data = array();
        $data['rows'] = $rows;

        $this->main = $this->load->view('admin/pcategory/pcategory_tree', $data, true);

        $this->execute();

    }

    function help_view_tree($tmp/*$categories*/, $parent = ''/*0*/, $space = ''){
        $items = '';
        $result = array();
        if(isset($tmp[$parent])){
            $num_record = count($tmp[$parent]);
            foreach($tmp[$parent] as $k => $v){
                $parent = $v->code;
                $value = $v->code;
                $label = $v->vi_name;
                $selected = '';
                $v->vi_name = $space . $v->vi_name;
                //$items .= eval($this->loadTemplate('admin/option_ddl.tpl'));
                $result[] = $v;
                //$items .=$this->help_view_tree($tmp/*$categories*/ , $parent, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                //$result = array_merge($result, $this->help_view_tree($tmp/*$categories*/ , $parent, $space . '|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'));
                $result = array_merge($result, $this->help_view_tree($tmp/*$categories*/ , $parent, $space . '|-------'));
            }
        }

        return $result;

    }

    function loadItems(){
            /*$item = '';
            $items = $this->pcategory->getAll();
            $this->setTemplate(array ('admin/pcategory/pcategory_item.tpl'));
            for($i = 0; $i < count($items); $i++){
                $id = $items[$i]->id_pcategory;
                $name = $items[$i]->vi_name;
                $description = $items[$i]->vi_description;
                $item .= eval ($this->loadTemplate('admin/pcategory/pcategory_item.tpl'));
            }

            return $item;*/
    }


    function edit_news_category($id){

        $this->setTemplate('edit_news_category.tpl');
        $code = uniqid();
        $this->session->set_userdata('code', $code);
        $this->load->model('news_category_model', 'category', true);
        $category = $this->category->getById($id);

        if(!$category){
            redirect('category/view_news_category');
        }

        $txtID = $category->category_id;
        $txtNameVi = $category->name_vi;
        $txtNameEn = $category->name_en;
        $txtDescriptionVi = $category->description_vi;
        $txtDescriptionEn = $category->description_en;
        $cbActive = $category->active == 1 ? 'checked' : '';
        $error_message = '';
        $picture = $category->picture == "" ? "" : "<img src='".$this->base_url."data/categories/news/{$category->picture}' width=150 height=50";
        $category_parent = $this->buidDDProductCategoryList('ddlParentCategory', $category->category_parent_id);
        $content = eval($this->loadTemplate('edit_news_category.tpl'));
        $this->execute($content);
    }

    function view_news_category(){

        $this->load->model('news_category_model', 'category', true);
        $categories = $this->category->getAll();

        $this->setTemplate(array('news_categories.tpl', 'news_categories_item.tpl'));
        $items = $this->loadNewsItems($categories);
        $content = eval($this->loadTemplate('news_categories.tpl'));
        $this->execute($content);
    }

    function loadNewsItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1){
        $items = '';
        if(!$categories){
            $categories = $this->category->getAll();
        }
        $tmp = array();
        for($i = 0; $i <count($categories); $i++){
            $category = $categories[$i];
            $tmp[$category->category_parent_id][$category->category_id] = $category;
        }


        if(isset($tmp[$parent])){
            $num_record = count($tmp[$parent]);
            foreach($tmp[$parent] as $k => $v){
                $parent = $v->category_id;
                $category_id = $v->category_id;
                $category_name = $v->name_vi;
                if($index%2 == 0) $class = 'class="bg"';
                else $class = '';
                $items .= eval($this->loadTemplate('news_categories_item.tpl'));
                //if(in_array($v->category_id, $track))
                $index++;
                $items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
            }

                /*for($j = 1; $j <= count($tmp[$parent]); $j++){
                    if(isset($tmp[$parent][$j])){
                        $category = $tmp[$parent][$j];
                        $parent = $category->category_id;
                        $category_id = $category->category_id;
                        $category_name = $category->name;
                        if($index%2 == 0) $class = 'class="bg"';
                        else $class = '';
                        $items .= eval($this->loadTemplate('product_categories_item.tpl'));
                        //if(in_array($v->category_id, $track))
                        $index++;
                        $items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
                    }
                }*/
        }
        //print_r($categories);
        return $items;
    }

    function view_product_category(){
        $this->load->model('product_category_model', 'category', true);
        $categories = $this->category->getAll();
        $items = $this->loadProductItems($categories);
        $content = eval($this->loadTemplate('product_categories.tpl'));
        $this->execute($content);
    }

    function loadProductItems($categories = null, $parent = 0, $track = array(), $style = 1, $index = 1){
        $items = '';
        if(!$categories){
            $categories = $this->category->getAll();
        }
        $tmp = array();
        for($i = 0; $i <count($categories); $i++){
            $category = $categories[$i];
            $tmp[$category->category_parent_id][$category->category_id] = $category;
        }


        if(isset($tmp[$parent])){
            $num_record = count($tmp[$parent]);
            foreach($tmp[$parent] as $k => $v){
                $parent = $v->category_id;
                $category_id = $v->category_id;
                $category_name = $v->name_vi;
                if($index%2 == 0) $class = 'class="bg"';
                else $class = '';
                $items .= eval($this->loadTemplate('product_categories_item.tpl'));
                //if(in_array($v->category_id, $track))
                $index++;
                $items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
            }

                /*for($j = 1; $j <= count($tmp[$parent]); $j++){
                    if(isset($tmp[$parent][$j])){
                        $category = $tmp[$parent][$j];
                        $parent = $category->category_id;
                        $category_id = $category->category_id;
                        $category_name = $category->name;
                        if($index%2 == 0) $class = 'class="bg"';
                        else $class = '';
                        $items .= eval($this->loadTemplate('product_categories_item.tpl'));
                        //if(in_array($v->category_id, $track))
                        $index++;
                        $items .=$this->loadProductItems($categories , $parent, $track, $style + 1, $index);
                    }
                }*/
        }
        //print_r($categories);
        return $items;
    }

    function buidDDProductCategoryList($name, $default){
        //$this->load->model('pcategory_model', 'category', true);
        $categories = $this->pcategory->getAll();
       // print_r($categories);
        //$this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        //$name = 'Parent';
        $value = '';
        $selected = '';
        $space= '';
        $label = 'Parent';
        $class = '';
        $action = '';
        $style = '';

        $tmp = array();
        for($i = 0; $i <count($categories); $i++){
            $category = $categories[$i];
            //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
            $tmp[$category->code_parent][$category->code] = $category;
        }

        //$options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($tmp/*$categories*/, '', $default);
        $options = $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true) . $this->getCategoryOption($tmp/* $categories */, '', $default);
        $data = array();
        $data['name'] = $name;
        $data['style'] = $style;
        $data['class'] = $class;
        $data['action'] = $action;
        $data['options'] = $options;
        return $this->load->view('admin/select', $data, true);
        //return eval($this->loadTemplate('admin/ddl.tpl'));
    }

    function buidDDNewsCategoryList($name, $default){
        $this->load->model('news_category_model', 'category', true);
        $categories = $this->category->getAll();
        $this->setTemplate(array('admin/option_ddl.tpl', 'admin/ddl.tpl'));
        $space = '';
        $name = 'Parent';
        $value = 0;
        $selected = '';
        $options = eval($this->loadTemplate('admin/option_ddl.tpl')) . $this->getCategoryOption($categories, 0, $default);
        return eval($this->loadTemplate('admin/ddl.tpl'));
    }

    function getCategoryOption($tmp/*$categories*/, $parent = ''/*0*/, $default = ''/*0*/, $space = '&nbsp;'){
        $items = '';
            /*if(!$categories){
                $categories = $this->pcategory->getAll();
            }*/
            /*$tmp = array();
            for($i = 0; $i <count($categories); $i++){
                $category = $categories[$i];
                //$tmp[$category->id_parent_pcategory][$category->id_pcategory] = $category;
                $tmp[$category->code_parent][$category->code] = $category;
            }*/
        //print_r($tmp);
        if(isset($tmp[$parent])){
            $num_record = count($tmp[$parent]);
            foreach($tmp[$parent] as $k => $v){
                //$parent = $v->id_pcategory;
                //$value = $v->id_pcategory;
                //echo '<br>\n'.$parent . '_\n';
                $parent = $v->code;
                $value = $v->code;
                $label = $v->vi_name;
                $selected = '';
                if($value == $default) $selected = 'selected';
                $items .= $this->load->view('admin/option_select', array('value' => $value, 'selected' => $selected, 'space' => $space, 'label' => $label), true);
                $items .=$this->getCategoryOption($tmp/* $categories */, $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
                
                //$items .= eval($this->loadTemplate('admin/option_ddl.tpl'));

                //$items .=$this->getCategoryOption($tmp/*$categories*/ , $parent, $default, $space . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
            }
        }

        return $items;
    }

    function test(){
        $email_address = "sd_sd@ere.re-hggh,rr";
           /* $result = ereg("/^[A-Z]+$/", $email_address);
             if($result)
            {
                echo "Khong hop le: " . $email_address . "<br>";
            }
            else
                echo "Hop le: " . $email_address . "<br>";
           //echo "<br>" . time();
           */
        echo  eregi('[^a-z0-9_@,;.-]', $email_address) ? 'Invalid' : 'Valid';
    }
    function save(){
        //$this->setTemplate('form_new_ncategory.tpl');
        $txtID = (int)trim($this->input->post('txtID'));
        $txtCode =  /*preg_replace("/[".VALID_CHARACTERS."]/", "", trim($this->input->post('txtCode')));*/ trim($this->input->post('txtCode'));
        $txtLinkRewrite = trim($this->input->post('txtLinkRewrite'));
        $category = null;
        if($txtID > 0){
            $category = $this->pcategory->getById($txtID);
            $data = $category;
        }
        else{
            
            $data['id_pcategory'] = 0;
            $data['code'] = '';
            $data['image'] = '';
            //$category->code_parent = '';
        }

        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        if(($txtCode!=$category['code'] AND $txtID > 0) OR $txtID==0){
            $this->form_validation->set_rules('txtCode', 'lang:category_code', 'required|min_length[2]|max_length[120]|callback_code_check|callback_code_validate_check');
            //echo $txtCode.' '.$category->code; return;
        }else
        $this->form_validation->set_rules('txtCode', 'lang:category_code', 'required|min_length[2]|max_length[120]|callback_code_validate_check');
        //$this->form_validation->set_rules('parent', 'lang:parent_code', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('txtViName', 'lang:vi_name', 'required|min_length[2]|max_length[120]');
        $this->form_validation->set_rules('txtEnName', 'lang:en_name', 'required|min_length[2]|max_length[120]');
        if($txtLinkRewrite!='' AND $txtLinkRewrite!=$category['link_rewrite'])
        $this->form_validation->set_rules('txtLinkRewrite', 'lang:friendly_url', 'callback_friendly_url_check');
            /*$this->form_validation->set_rules('password', 'Password', 'required');
            $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required');
            */

        if(empty($category) AND $txtID > 0){
            redirect('addmin/pcategory/view');
            return;
        }

        $data['code'] = /*preg_replace("/[".VALID_CHARACTERS."]/", "", trim($this->input->post('txtCode')));*/ trim($this->input->post('txtCode'));
        $data['code_parent'] = trim($this->input->post('parent'));
        $data['vi_name'] = trim($this->input->post('txtViName'));
        $data['en_name'] = trim($this->input->post('txtEnName'));
        $data['vi_description'] = trim($this->input->post('txtViDescription'));
        $data['en_description'] = trim($this->input->post('txtEnDescription'));
        $data['link_rewrite'] = trim($this->input->post('txtLinkRewrite'));
        $data['meta_description'] = trim($this->input->post('txtMetaDescription'));
        $data['meta_title'] = trim($this->input->post('txtMetaTitle'));
        $data['meta_keywords'] = trim($this->input->post('txtMetaKeywords'));
        $data['active'] = (int)$this->input->post('active');
        $data['module'] = trim($this->input->post('module'));
        $data['date_upd'] = date('Y-m-d H:i:s', time());
        $error_message =''; // $this->loadErrorMessage('Thong diep loi.');
        $category_parent = ''; //$this->buidDDNewsCategoryList('ddlParentCategory', 0);

        $attach_image = false;
        $image_upload = array('error'=> false);
        if(isset($_FILES['file']['tmp_name']) AND strlen($_FILES['file']['tmp_name']) > 0){
            $attach_image = true;
            $image_upload = $this->upload_image('file', CATEGORY_IMAGE_PATH /*'./Data/Images/Product/'*/);
            if($image_upload['error'])
            $error_message .= $image_upload['message'];

        }

        if ($this->form_validation->run() == FALSE OR ($attach_image == true AND $image_upload['error']==true)){
            //$code = uniqid();
            //$this->session->set_userdata('code', $code);
            $error_message = validation_errors(). '<br>'. $error_message;
           
            //$data['category'] = $category;
            $data['ddlPatentCategory'] = $this->buidDDProductCategoryList('parent', $category['code_parent']);
            $data['error_message'] = '<div style="color:red">' . $error_message.'</div>';
            //if()
            $data['legend_text'] = $txtID>0 ?  lang('edit_product_category') : lang('create_product_category');
            $this->template->parse_view('content', 'admin/pcategory/create_pcategory', $data);
        	$this->template->render();
            return;
        }
        else{
            if($attach_image){
                $file_path = CATEGORY_IMAGE_PATH . $image_upload['upload_data']['file_name'];
                if($txtID > 0 AND $data['image']!=$image_upload['upload_data']['file_name']) {
                    @unlink(CATEGORY_IMAGE_PATH.$data['image']);
                }

                $data['image'] = $image_upload['upload_data']['file_name'];
            }

            if($data['code_parent']!=""){
                $parent_cat = $this->pcategory->getByCode($data['code_parent']);
                $data['id_parent_pcategory'] = $parent_cat['id_pcategory'];
            }
            else $data['id_parent_pcategory'] = 0;

            if($txtID > 0){
                $result = $this->pcategory->update($data);
            }
            else{
                $data['number_product'] = 0;
                $data['level_depth'] = 0;
                $data['date_add'] = date('Y-m-d H:i:s', time());
                $result = $this->pcategory->create($data);

            }

            //redirect('admin/pcategory/view');
            redirect($this->session->userdata("his_adm"));
        }

    }

    function code_check($code){
        $result = $this->pcategory->getByCode($code);
        if ($result!=null){
            $this->form_validation->set_message('code_check', '%s is not available.');
            return FALSE;
        }
        else{
            return TRUE;
        }
    }

    function code_validate_check($code){
        if(preg_match('/[^a-zA-Z0-9_@,:;.-]/', $code)){ // ^a-zA-Z0-9_\-,.:            ^a-z0-9_@,.-
            //? 'Invalid' : 'Valid';
            $this->form_validation->set_message('code_validate_check', '%s is invalid.');
            return FALSE;
        }
        else{
            return TRUE;
        }
    }

    function friendly_url_check($url){
        $result = $this->pcategory->getByLinkRewrite($url);
        if ($result!=null){
            $this->form_validation->set_message('friendly_url_check', '%s is not available.');
            return FALSE;
        }
        else{
            return TRUE;
        }
    }

    function testGetFile(){
        $config = array(
            'allowed' => array('JPEG', 'jpg', 'PNG', 'png', 'GIF', 'gif'),
            'max_size'=> 1024000000 /*1Mb*/
        );

        $result = getFile($config, 'Data', 'http://images8.dantri.com.vn/ThumbImages/Uploaded/2009/05/08/lut080520094_327.jpg');

        if(!$result['error']) echo 'Get file success.';
        else echo $result['message'];

    }

    function delete1(){
        $this->load->model('file_model', 'file', true);
        $id = intval($this->uri->segment(4));
        if($id>0){
            //$this->pcategory->delete($id);
            $ids = array($id);
        }
        else{
            if(($this->input->post('submitDelcategory'))){
                $ids = $this->input->post('categoryBox');
            }
        }

        $tmp_ids_product = array();
        $tmp_ids = array();
        if(count($ids)){
            for($i = 0; $i < count($ids); $i++){
                $tmp_ids = array_merge($tmp_ids, getElementsOfNode($ids[$i]));
            }
            $ids = array_merge($tmp_ids, $ids);

            $ids_string = implode(",", $ids);
            //Delete file
            $files = $this->file->findByCategories($ids);
            $ids_file = array();
            for($j = 0; $j < count($files); $j++){
                $ids_file = $files[$j]->id_file;
            }
            $this->file->delete($ids_file);

            //Delete product
            $products = $this->product->getFindByCategories($ids);
            $ids_product = array();
            for($j = 0; $j < count($products); $j++){
                $ids_product = $products[$j]->id_product;
            }
            $this->product->delete($ids_product);
            
            //Delete sub category
            
        }

        //redirect('admin/pcategory');
        //redirect($_SESSION["his_adm"]);
    }

    function delete(){
        $id = intval($this->uri->segment(4));
        if($id>0)
        	$this->pcategory->delete($id);
        else{
            if(($this->input->post('submitDelcategory'))){
                $ids = $this->input->post('categoryBox');
                if(count($ids))
                $this->pcategory->delete($ids);
            }
        }

        redirect('admin/pcategory');
        //redirect($this->session->userdata('his_adm'));
    }

    function change_order(){
        $id1 = (int)$this->uri->segment(4);
        $id2 = (int)$this->uri->segment(5);

        $cat1 = $this->pcategory->getById($id1);
        $cat2 = $this->pcategory->getById($id2);

        if($cat1 AND $cat2){
            $position1 = $cat1->order_view;
            $cat1->order_view = $cat2->order_view;
            $cat2->order_view = $position1;

            $this->pcategory->update($cat1);
            $this->pcategory->update($cat2);

        }

        redirect($_SESSION['his_adm']);
    }

}
?>
